
//记载插件
const fs = require('fs')
const Student = require('./student')

//express封装route
const express = require('express')
const router = express.Router()


router.get('/students', (req, res) => {
    //第二个参数，传入编码方式
    Student.find((err, students) => {
        if (err) return res.status(500).send('Server error')
        res.render('index.html', {
            fruits: [
                '提子',
                '榴莲',
                '芒果',
                '蓝莓'
            ],
            students: students
        })
    })
})

router.get('/students/new', (req, res) => {
    res.render('new.html')

})

router.post('/students/new1', (req, res) => {
    Student.save(req.body,(err,data) => {
        if (err) return res.status(500).send('Server error')
    })

    res.redirect('/students')

})

router.get('/students/edit', (req, res) => {
    let id = parseInt(req.query.id) 
    Student.findBI(id,(err,stu) => {
        if (err) return res.status(500).send('Server error')
        res.render('edit.html',{
            student:stu
        })
    })
    
    

})

router.post('/students/edit1', (req, res) => {
    let student = req.body
    // console.log(student)
    Student.edit(student,(err) => {
        if (err) return console.log('修改失败')
        console.log('修改成功')
        res.redirect('/students')
    })

})

router.get('/students/delete', (req, res) => {
    let id = parseInt(req.query.id) 
    Student.delete(id,(err) => {
        if (err) return res.status(500).send('Server error')
    })
    res.redirect('/students')
})
//需要暴露出来，不然app中加载不到router模块;修改需重启
module.exports = router


//自己封装路由
// module.exports = (app) => {
//     app.get('/students',(req,res) => {
//         //第二个参数，传入编码方式
//         fs.readFile('./db.json',"utf8",(err,data) => {
//             if(err) return res.status(500).send('Server error')
//             res.render('index.html',{
//                 fruits:[
//                     '提子',
//                     '榴莲',
//                     '芒果',
//                     '蓝莓'
//                 ],
//                 students:JSON.parse(data).students
//             })
//         })
//     })

//     app.get('/students/new',(req,res) => {


//     })

//     app.get('/students/new',(req,res) => {


//     })

//     app.get('/students/edit',(req,res) => {


//     })

//     app.get('/students/edit',(req,res) => {


//     })

//     app.get('/students/delet',(req,res) => {


//     })
// }


